<template>
  <div id="dictComponent">
    <div>
      <div class="filter-container">
        <!-- <div class="filter-item">
          <span class="span">实体数据 </span>
          <el-input v-model="listQuery.keyword" style="width: 200px;" placeholder="请输入字典标签或值"
            @keyup.enter.native="handleFilter" />
        </div>
        <el-button v-permission="['sys:dict:list']" v-waves class="filter-item" type="primary" icon="el-icon-search"
          @click="handleFilter">{{ $t('table.search') }}</el-button> -->
        <el-button v-permission="['sys:dict:add']" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
      </div>

      <el-table :key="tableKey" v-loading="listLoading" :data="temp.labelGroup" element-loading-text="正在加载，请稍后" border fit highlight-current-row style="width: 100%">
        <el-table-column label="列名" min-width="150px">
          <template slot-scope="{row}">
            <span>{{ row.columnName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="标签名" min-width="150px">
          <template slot-scope="{row}">
            <span>{{ row.labelName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标签值" min-width="150px">
          <template slot-scope="{row}">
            <span>{{ row.labelValue }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.actions')" align="center" width="180" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button v-permission="['sys:dict:update']" size="small" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row,scope.$index)">{{ $t('table.edit') }}</el-button>
            <el-button v-permission="['sys:dict:delete']" size="small" type="text" icon="el-icon-delete" class="delete-text-btn" @click="handleDelete(scope.$index)">{{ $t('table.delete') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination :current-page.sync="listQuery.page" :page-sizes="pageArray" :page-size="listQuery.limit" :total="total" background layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>

    </div>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :append-to-body="true" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="query" label-position="left" label-width="120px" style="width: 80%; margin-left:50px;">
        <el-row :gutter="40">
          <el-col :span="24">
            <el-form-item label="列名" prop="columnName">
              <el-select v-model="query.columnName" class="filter-item" placeholder="请选择列名" @change="changeColumn">
                <el-option v-for="(item, index) in columnData" :key="index" :label="item.columnName" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="标签名" prop="labelname">
              <el-select v-model="query.labelName" class="filter-item" placeholder="请选择标签名" :disabled="true">
                <el-option v-for="(item, index) in labelData" :key="index" :label="item.labelName" :value="item.labelName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="标签值" prop="labelValue">
              <el-select v-model="query.labelValue" class="filter-item" placeholder="请选择标签值" :disabled="!query.columnName">
                <el-option v-for="(item, index) in counteData" :key="index" :label="item.label" :value="item.label" />
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" :loading="loading" @click="dialogStatus === 'create' ? createData() : updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
      <!-- <div class="el-message el-message--error"><p>请填写完整</p></div> -->
    </el-dialog>
  </div>
</template>

<script>
import { fetchDictList, createDict, deleteDict, updateDict } from '@/api/sys/dict'
import { labelEntityList, entityTable, addEntiyt, updateEntiyt } from '@/api/metadata/entity'
import { getColumns, getLabelcount } from '@/api/metadata/entity'
import permission from '@/directive/permission/permission'
import waves from '@/directive/waves' // 水波纹指令
import store from '@/store'

export default {
  name: 'SysDictComponent',
  directives: {
    waves,
    permission,
  },
  data() {
    return {
      dictGroup: {},
      tableKey: 0,
      total: 0,
      listLoading: false,
      pageArray: this.$store.getters.pageArray,
      showReviewer: false,
      temp: {
        name: '',
        tableId: '',
        labelGroup: [],
      },
      query: {
        columnName: '', //列名
        labelName: '', //标签名
        labelValue: '', //标签值
      },
      loading: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑字典',
        create: '添加字典',
      },
      rules: {},
      distList: [],
      listQuery: {},
      downloadLoading: false,
      columnData: [], //列名
      labelData: [], //标签名
      counteData: [], //标签值
      updateIndex: '',
    }
  },
  methods: {
    //选择列
    changeColumn(item) {
      console.log(item)
      this.query = {
        columnId: item.id,
        columnName: item.columnName,
        labelName: item.label,
        labelId: item.labelId,
      }
      //获取下拉标签值
      getLabelcount(item.labelId).then((res) => {
        // console.log(res,'标签值')
        if (res.data.code == 200) {
          this.counteData = res.data.data
        }
      })
    },
    getList(row, tableId) {
      console.log(row, tableId)
      this.total = row.labelGroup ? row.labelGroup.length : 0
      this.temp.id = row.id
      this.temp.tableId = tableId
      this.temp.name = row.name
      this.temp.labelGroup = row.labelGroup ? row.labelGroup : []
      console.log(this.temp, '11temp')
      getColumns({ tableId: this.temp.tableId }).then((res) => {
        if (res.data.code == 200) {
          this.columnData = res.data.data
        }
      })
      // entityTable(row.id).then(res => {
      //     console.log(res, '实体数据')
      //     if (res.data.code == 200) {
      //         this.distList = res.data.data.labelGroup
      //     }
      // })
      // this.listLoading = true
      // fetchDictList(this.listQuery).then(response => {
      //   this.list = response.data.data
      //   this.total = response.data.total
      //   this.listLoading = false
      // })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success',
      })
      row.status = status
    },
    resetTemp() {
      this.loading = false
      this.temp = {
        tableId: '',
        name: '',
        labelGroup: [],
      }
    },
    refreshGroupDict(row) {
      this.listQuery.gid = row.id
      this.listQuery.page = 1
      this.listQuery.keyword = ''
      this.dictGroup = row
      this.getList()
    },
    handleCreate() {
      if (this.temp.name === '' || this.temp.tableId === '') {
        this.$message.error('请选择实体名称')
      } else {
        this.query = {
          columnName: '', //列名
          labelName: '', //标签名
          labelValue: '', //标签值
          columnId: '',
          labelId: '',
        }
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      }
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.labelGroup.push(this.query)
          console.log(this.temp, 'temp')
          updateEntiyt(this.temp).then((res) => {
            console.log(res, '添加')
            if (res.data.code == 0) {
              this.dialogFormVisible = false
              this.$message.success(res.data.msg)
            } else {
              this.$message.error(res.data.msg)
            }
          })
        }
      })
    },
    handleUpdate(row, index) {
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.updateIndex = index
      this.query = row
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.temp.labelGroup[this.updateIndex] = this.query
      updateEntiyt(this.temp).then((res) => {
        console.log(res, '添加')
        if (res.data.code == 0) {
          this.dialogFormVisible = false
          this.$message.success(res.data.msg)
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    handleDelete(index) {
      this.$confirm('确定删除该数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.temp.labelGroup.splice(index, 1)
        updateEntiyt(this.temp).then((res) => {
          console.log(res, '添加')
          if (res.data.code == 0) {
            this.$message.success(res.data.msg)
          } else {
            this.$message.error(res.data.msg)
          }
        })
      })
    },
  },
}
</script>
<style>
.span {
  color: #606266;
  font-weight: 700;
  font-size: 14px;
}
</style>